import React, { useState, useEffect } from 'react';
import axios from 'axios';

import './AddMemberModal.css';
import '../../../assets/icons/iconfont.css';
import Icon from '../../Icon';

interface UserData {
  _id?: string;
  username: string;
  image: string;
  isLoggedIn: boolean;
}

interface AddMemberModalProps {
  isOpen: boolean;
  onClose: () => void;
  onAddMember: (userId: string) => void;
  currentGroupId: string;
  currentMembers: UserData[];
  currentUser: UserData;
}

const AddMemberModal: React.FC<AddMemberModalProps> = ({
  isOpen,
  onClose,
  onAddMember,
  currentMembers,
  currentUser,
}) => {
  const [users, setUsers] = useState<UserData[]>([]);
  const [loading, setLoading] = useState(false);
  const [searchTerm, setSearchTerm] = useState('');
  const [selectedUsers, setSelectedUsers] = useState<string[]>([]);

  // 获取所有用户列表
  useEffect(() => {
    if (isOpen) {
      fetchUsers();
    }
  }, [isOpen]);

  const fetchUsers = async () => {
    try {
      setLoading(true);
      const response = await axios.get(
        `http://localhost:3001/ysx/users?currentUser=${currentUser.username}`
      );

      if (response.data.code === 200) {
        // 过滤掉已经是群成员的用户
        const currentMemberUsernames = currentMembers.map(
          member => member.username
        );
        const availableUsers = response.data.data.filter(
          (user: UserData) => !currentMemberUsernames.includes(user.username)
        );
        setUsers(availableUsers);
      }
    } catch (error) {
      console.error('获取用户列表失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 过滤用户列表
  const filteredUsers = users.filter(user =>
    user.username.toLowerCase().includes(searchTerm.toLowerCase())
  );

  // 处理用户选择
  const handleUserSelect = (userId: string) => {
    setSelectedUsers(prev => {
      if (prev.includes(userId)) {
        return prev.filter(id => id !== userId);
      } else {
        return [...prev, userId];
      }
    });
  };

  // 添加选中的用户
  const handleAddSelectedUsers = async () => {
    if (selectedUsers.length === 0) {
      alert('请选择要添加的用户');
      return;
    }

    try {
      for (const userId of selectedUsers) {
        await onAddMember(userId);
      }

      setSelectedUsers([]);
      onClose();
    } catch (error) {
      console.error('添加群成员失败:', error);
      alert('添加群成员失败，请重试');
    }
  };

  if (!isOpen) return null;

  return (
    <div className="add-member-modal-overlay">
      <div className="add-member-modal">
        <div className="add-member-modal-header">
          <button className="cancel-btn" onClick={onClose}>
            取消
          </button>
          <h3>添加群成员</h3>
          <button
            className="confirm-btn"
            onClick={handleAddSelectedUsers}
            disabled={selectedUsers.length === 0}
          >
            确定({selectedUsers.length})
          </button>
        </div>

        <div className="add-member-modal-content">
          {/* 搜索框 */}
          <div className="search-container">
            <input
              type="text"
              placeholder="搜索用户"
              value={searchTerm}
              onChange={e => setSearchTerm(e.target.value)}
              className="search-input"
            />
            <Icon iconClass="icon-search" />
          </div>

          {/* 用户列表 */}
          <div className="users-list">
            {loading ? (
              <div className="loading">加载中...</div>
            ) : filteredUsers.length === 0 ? (
              <div className="no-users">
                {searchTerm ? '没有找到匹配的用户' : '没有可添加的用户'}
              </div>
            ) : (
              filteredUsers.map(user => (
                <div
                  key={user._id || user.username}
                  className={`user-item ${selectedUsers.includes(user._id || user.username) ? 'selected' : ''}`}
                  onClick={() => handleUserSelect(user._id || user.username)}
                >
                  <div className="user-avatar">
                    {user.image ? (
                      <img src={user.image} alt={user.username} />
                    ) : (
                      <div className="default-avatar">
                        {user.username.charAt(0).toUpperCase()}
                      </div>
                    )}
                  </div>
                  <div className="user-info">
                    <div className="user-name">{user.username}</div>
                  </div>
                  <div className="user-checkbox">
                    {selectedUsers.includes(user._id || user.username) && (
                      <Icon iconClass="icon-check" />
                    )}
                  </div>
                </div>
              ))
            )}
          </div>
        </div>
      </div>
    </div>
  );
};

export default AddMemberModal;
